package cn.ctyun.xstore


import com.amazonaws.auth.BasicAWSCredentials
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility
import com.amazonaws.mobileconnectors.s3.transferutility.UploadOptions
import com.amazonaws.regions.Region
import com.amazonaws.regions.Regions
import com.amazonaws.services.s3.AmazonS3Client
import java.io.InputStream


private const val ENDPOINT = ""

private const val AK = ""

private const val SK = ""

private const val BUCKET = ""

private val s3Client: AmazonS3Client by lazy {
    val client =
        AmazonS3Client(BasicAWSCredentials(AK, SK), Region.getRegion(Regions.DEFAULT_REGION))
    client.endpoint = ENDPOINT
    client
}

private val s3Transfer: TransferUtility by lazy {
    /**
     * ctx 来自 Application，如果这些代码写在 Service 或者 Activity 里，可以通过 applicationContext
     * defaultBucket 可以不设置，如果不设置，在上传时，可以通过 UploadOptions 来设置。
     */
    TransferUtility.builder().s3Client(s3Client).context(ctx).defaultBucket(BUCKET).build()
}

fun loadObjectNames(size: Int): List<String> {

    val objects = s3Client.listObjectsV2(BUCKET)
    val objectNames = ArrayList<String>()

    for (prefix in objects.commonPrefixes) {
        objectNames.add(prefix)
    }
    for (obj in objects.objectSummaries) {
        objectNames.add(obj.key)
    }
    return objectNames
}

fun upload(key: String, fileInputStream: InputStream?, transferListener: TransferListener?) {
    if (fileInputStream == null) return

    val observer = s3Transfer.upload(key, fileInputStream)
    // 如果 TransferUtility 没有设置 defaultBucket，则需要通过以下方法来设置 bucket
    // val options = UploadOptions.builder().bucket(BUCKET).build()
    // val observer = s3Transfer.upload(key, fileInputStream, options)

    observer.setTransferListener(transferListener)
}